#!/bin/bash

if [ ! -w /srv/docker ]; then
	sudo chmod g+w /srv/docker
fi


GITHUB_URL_PREFIX=https://gh-proxy.com/
install_overleaf() {
    if [ ! -d /srv/docker/overleaf/overleaf/.git ]; then
        git clone ${GITHUB_URL_PREFIX}https://github.com/overleaf/overleaf.git /srv/docker/overleaf/overleaf
    fi

    if [ ! -d /srv/docker/overleaf/toolkit/.git ]; then
        git clone ${GITHUB_URL_PREFIX}https://github.com/overleaf/toolkit.git /srv/docker/overleaf/toolkit
    fi

    pushd /srv/docker/overleaf/toolkit
    bin/init --tls
    bin/up -d
    popd
}

build_sharelatex() {
    docker build overleaf -t xlchen/sharelatex
}

install_sharelatex() {
    sudo mkdir -p /srv/docker/sharelatex
    sudo chgrp docker /srv/docker/sharelatex
    sudo chmod g+w /srv/docker/sharelatex
    cp ./overleaf/docker-compose.yml /srv/docker/sharelatex
    pushd /srv/docker/sharelatex
    docker compose up -d
}

echo "Running $0 with $?" 
build_sharelatex
install_sharelatex
